/*
 * Copyright (C) 2010  Yigal Duppen
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package nl.scalasim;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.MessageFormat;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

/**
 * Compact Formatter for JDK logging.
 *
 * @author Yigal Duppen
 * @since Oct 26, 2010
 */
public class CompactFormatter extends Formatter {

    @Override
    public String format(LogRecord record) {
        StringWriter buffer = new StringWriter();
        PrintWriter out = new PrintWriter(buffer);

        String source = record.getSourceClassName()
                .substring(
                        record.getSourceClassName().lastIndexOf('.') + 1);
        if (source.contains("$")) {
            source = source.substring(0, source.indexOf('$'));
        }


        String message;
        if (record.getParameters() != null) {
            message = MessageFormat
                    .format(record.getMessage(), record.getParameters());
        } else {
            message = record.getMessage();
        }

        out.println(String.format("%7s %s - %s",
                record.getLevel(),
                source,
                message));

        if (record.getThrown() != null) {
            record.getThrown().printStackTrace(out);
        }

        out.close();
        return buffer.toString();
    }


}
